package com.study.favorite.servlet;

import com.google.gson.Gson;
import com.study.favorite.mapper.TagMapper;
import com.study.favorite.pojo.Tag;
import com.study.favorite.util.MybatisHelper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/allTag.s")
public class AllTagServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try(SqlSession sqlSession = MybatisHelper.openSession()) {
            TagMapper mapper = sqlSession.getMapper(TagMapper.class);
            List<Tag> tags = mapper.selectAll();
            // tags ==> json
            Gson gson = new Gson();
            String s = gson.toJson(tags);
            resp.setContentType("text/html; charset=utf-8");
            resp.getWriter().append(s);
            for (Tag tag : tags) {
                System.out.println(tag);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

}
